package com.cn.codebrush.二分查找;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Author Boolean
 * @Date 2022/5/10 11:26
 * @Version 1.0
 */
public class No34在排序数组中查找元素的第一个和最后一个位置 {
    public static void main(String[] args) {
        int[] nums = {};
        int[] nums1 = {5};
        int[] nums2 = {5,5};
        int[] nums3 = {5,7,7,8,8,10};
        System.out.println(searchRange(nums3,6));
    }

    public static int[] searchRange(int[] nums, int target) {
        int[] res = {-1,-1};
        int n = nums.length;
        List list = new ArrayList();
        int left=0,right=n-1;
        while(left <= right){
            int mid = (left+right)/2;
            if(nums[mid] == target){
                left = mid; right = mid;
                while(left>=0 && nums[left] == target){
                    list.add(left--);
                }
                while(right<n && nums[right] == target){
                    list.add(right++);
                }
                break;
            }else if(nums[mid] > target){
                right = mid;
            }else {
                left = mid+1;
            }
            if(left == right && nums[left] != target){
                break;
            }
        }
        Collections.sort(list);
        if(list.size()>0){
            res[0] = (int) list.get(0);
            res[1] = (int) list.get(list.size()-1);
        }
        return res;

    }
}
